/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    struct Compare {
        typedef ListNode * ListNodePtr;
        bool operator()(const ListNodePtr &a, const ListNodePtr &b) const {
            return a->val > b->val;
        }
    };

    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<ListNode*> q;
        for (int i = 0; i < lists.size(); ++i) {
            if (lists[i] != NULL) {
                q.push_back(lists[i]);
            }
        }

        ListNode *head = NULL;
        ListNode *tail = NULL;
        make_heap(q.begin(), q.end(), Compare());
        while (!q.empty()) {
            ListNode *cur = q[0];
            pop_heap(q.begin(), q.end(), Compare());
            q.pop_back();

            if (head == NULL) {
                head = tail = cur;
            } else {
                tail->next = cur;
                tail = tail->next;
            }
            if (cur->next) {
                q.push_back(cur->next);
                push_heap(q.begin(), q.end(), Compare());
            }
        }
        return head;
    }
};
